<?php

namespace Lib\Core;

class Ajax extends Request {

    private $func;

    /**
     * 设置ajax控制器调用的方法.
     *
     * @param  string $func 方法名称.
     *
     * @return $this
     */
    public function setFunction($func) {
        $this->func = $func;
        return $this;
    }

    /**
     * ajax 控制器运行.
     */
    public function run() {
        $function = $this->func;
        $this->actionBefore();
        $this->$function();
        $this->actionAfter();
    }

    public function response($data) {
        $data = array(
            'error' => 0,
            'data' => $data,
            'code' => 0,
        );
        echo json_encode($data);
        \Main::sysExit();
    }

    public function responseError($msg, $code = 1) {
        $data = array(
            'error' => 1,
            'data' => $msg,
            'code' => $code,
        );
        echo json_encode($data);
        \Main::sysExit();
    }

    /**
     * 执行actionIndex前调用.
     *
     * @return void
     */
    protected function actionBefore(){}

    /**
     * 执行actionIndex后调用.
     *
     * @return void
     */
    protected function actionAfter(){}
}